package com.gitee.httphelper.result;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * 默认返回处理
 * @author thc
 */
public class DefaultResponseResult implements ResponseResult {
    private final HttpResponse response;

    public DefaultResponseResult(HttpResponse response) {
        this.response = response;
    }

    @Override
    public int getStatus() {
        return response.getStatusLine().getStatusCode();
    }

    /**
     * 返回字符串结果，使用UTF_8编码
     *
     * @return 返回字符串结果
     * @throws IOException 请求失败抛出IO异常
     */
    @Override
    public String asString() throws IOException {
        HttpEntity entity = this.response.getEntity();
        try {
            return EntityUtils.toString(entity, StandardCharsets.UTF_8);
        } finally {
            closeResponse();
        }
    }

    /**
     * InputStream使用完毕后，需要手动调用close()
     *
     * @return 返回InputStream
     * @throws IOException 请求失败抛出IO异常
     * @see #closeResponse()
     */
    @Override
    public InputStream asStream() throws IOException {
        HttpEntity entity = this.response.getEntity();
        return entity.getContent();
    }

    @Override
    public Map<String, String> getHeaders() {
        Header[] allHeaders = response.getAllHeaders();
        if (allHeaders == null || allHeaders.length == 0) {
            return Collections.emptyMap();
        }
        Map<String, String> headers = new HashMap<>(allHeaders.length * 2);
        for (Header header : allHeaders) {
            headers.put(header.getName(), header.getValue());
        }
        return headers;
    }

    /**
     * 关闭response
     */
    @Override
    public void closeResponse() {
        if (response instanceof Closeable) {
            try {
                ((Closeable) response).close();
            } catch (IOException ignored) {
            }
        }
    }

    @Override
    public HttpResponse getResponse() {
        return response;
    }
}